<template>
  <u-modal
    v-model="modalShow"
    :content="modalContent"
    show-cancel-button="true"
    @confirm="confirm(id)"
    @cancel="cancel"
  ></u-modal>
  <view class="wrap">
    <!-- <u-button @click="clear">清空列表</u-button> -->
    <u-waterfall ref="uWaterfall" v-model="flowList">
      <template #left="{ leftList }" style="width: 200rpx">
        <view
          v-for="(item, index) in leftList"
          :key="index"
          class="demo-warter"
          @longpress="remove(item._id, index)"
          @click="moreInfo(item._id)"
        >
          <u-lazy-load
            threshold="600"
            border-radius="10"
            :image="item.image[0]"
            :index="index"
          >
          </u-lazy-load>
          <view class="demo-title">
            {{ item.title }}
          </view>
          <view class="demo-authorName" style="font-weight: 400">
            <u-image
              width="40rpx"
              height="40rpx"
              :src="item.authorAvatarUrl"
              shape="circle"
              style="margin-right: 20rpx"
            ></u-image>
            {{ item.authorName }}
            <view
              class="articleFavourite"
              @click.stop="
                favouriteIt(index, item._id) &&
                (item.favourite = !item.favourite) &&
                item.favourite
                  ? item.favouritesCount++
                  : item.favouritesCount--
              "
            >
              <u-icon
                :name="!item.favourite ? 'heart' : 'heart-fill'"
                :color="!item.favourite ? 'inherit' : 'red'"
                size="28"
              ></u-icon>
              {{ item.favouritesCount }}
            </view>
          </view>
        </view>
      </template>
      <template #right="{ rightList }">
        <view
          v-for="(item, index) in rightList"
          :key="index"
          class="demo-warter"
          @longpress="remove(item._id, index)"
          @click="moreInfo(item._id)"
        >
          <u-lazy-load
            threshold="600"
            border-radius="10"
            :image="item.image[0]"
            :index="index"
          >
          </u-lazy-load>
          <view class="demo-title">
            {{ item.title }}
          </view>
          <view class="demo-authorName">
            <u-image
              width="40rpx"
              height="40rpx"
              :src="item.authorAvatarUrl"
              shape="circle"
              style="margin-right: 20rpx"
            ></u-image>
            {{ item.authorName }}
            <view
              class="articleFavourite"
              @click.stop="
                favouriteIt(index, item._id) &&
                (item.favourite = !item.favourite) &&
                item.favourite
                  ? item.favouritesCount++
                  : item.favouritesCount--
              "
            >
              <u-icon
                :name="!item.favourite ? 'heart' : 'heart-fill'"
                :color="!item.favourite ? 'inherit' : 'red'"
                size="28"
              ></u-icon>
              {{ item.favouritesCount }}
            </view>
          </view>
        </view>
      </template>
    </u-waterfall>
    <u-loadmore
      bg-color="rgb(240, 240, 240)"
      :status="loadStatus"
      @loadmore="addRandomData()"
    ></u-loadmore>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, nextTick, onMounted, watch } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import {
  getArticles,
  likeArticle,
  deleteArticle,
} from '../../../utils/modules/article.js'
import { useContentStore } from '@/store/modules/indexContent'
import articlesData from '@/assets/json/atricles.json'
const contentStore = useContentStore()

const loadStatus = ref<String>('')
const flowList = ref<Array<any>>([])
const list = ref<Array<any>>([])
const modalShow = ref<Boolean>(false)
const modalContent = ref<String>('确认删除该动态嘛～')
const chooseId = ref<Number>(0)
const modalClickStatus = ref<Boolean>(false)
const that: any | null = getCurrentInstance().ctx

const props = defineProps<{
  currentTag: String
  currentPage: Number
}>()

function favouriteIt(index, id) {
  likeArticle({
    articleId: id,
    openId: uni.getStorageSync('openId') ? uni.getStorageSync('openId') : '',
  })
    .then((res) => {
      console.log(res)
    })
    .catch((err) => {
      console.log(err)
    })

  return true
}
function moreInfo(itemm) {
  const index = flowList.value.findIndex((item) => item._id == itemm)
  if (index !== -1) {
    uni.navigateTo({
      url: `/pages/article/article?id=${flowList.value[index]._id}`,
    })
  }
}

function addRandomData() {
  if (!contentStore.list.length) {
    for (let i = list.value.length - 1; i >= 0; i--) {
      const index = i
      // let index = Math.floor(Math.random() * (list.value.length - 1))
      // 先转成字符串再转成对象，避免数组对象引用导致数据混乱
      const item = JSON.parse(JSON.stringify(list.value[index]))
      // item.id = index
      item.id = list.value[i]._id
      flowList.value.push(item)
    }
    contentStore.list = flowList.value
  } else {
    flowList.value = contentStore.list
  }
}

function remove(id, index: any) {
  modalShow.value = true
  chooseId.value = id
  console.log(chooseId.value, '--------chooseId')

  modalClickStatus.value = true
  console.log(that.$refs.uWaterfall.$children[index])
}

//获取文章信息
function getArticlesList() {
  getArticles({
    tag: props.currentTag,
  }).then((res) => {
    list.value = res.data.articles
  })
}

// Modal框的操作
function confirm() {
  deleteArticle({
    articleId: chooseId.value,
  })
    .then((res) => {
      console.log(res, 'res')
      modalClickStatus.value = false
      modalShow.value = false
      that.$refs.uWaterfall.clear()
      flowList.value = []
      list.value = []
      getArticlesList()
      addRandomData()
      flowList.value = list.value
    })
    .catch((err) => {
      console.log(err, 'err')
    })
  // console.log(flowList.value)
}
function cancel() {
  modalClickStatus.value = false
}

//getArticlesList() //获取文章列表

//页面到达底部之后的操作
onReachBottom(() => {
  loadStatus.value = 'loading'
  // 模拟数据加载
  setTimeout(() => {
    addRandomData()
    loadStatus.value = 'loadmore'
  }, 1000)
})

//将渲染页面的函数放在这里 也会渲染就会在确定接收到数据之后再完成
nextTick(() => {
  addRandomData()
})

watch(
  () => list.value.length,
  (value, oldValue) => {
    if (list.value.length != 0) {
      that.$refs.uWaterfall.clear()
    }
    uni.showLoading({
      title: '加载中...',
    })
    nextTick(() => {
      getArticlesList()
      addRandomData()
      flowList.value = list.value
    })
    // uni.hideLoading()
  },
  { immediate: true },
)

watch(
  () => props.currentPage,
  (value, oldValue) => {
    if (value && value != oldValue) {
      console.log(`value,oldValue=====>${value}+${oldValue}`)
      that.$refs.uWaterfall.clear()
      flowList.value = []
      list.value = []
      nextTick(() => {
        getArticlesList()
        //   addRandomData()
      })
    }
  },
  { immediate: true },
)
getArticlesList()
//⬇渲染前做的操作
onMounted(() => {
  addRandomData()
  getArticlesList()
})
</script>

<style>
/* page不能写带scope的style标签中，否则无效 */
page {
  background-color: #f5f9fa;
}
</style>

<style lang="scss" scoped>
.demo-authorName {
  font-size: 26rpx;
  color: $u-tips-color;
  margin-top: 5px;
  display: flex;
  font-weight: 400;
  .articleFavourite {
    margin-left: auto;
    // margin-left: 20%;
    margin-top: 3px;
  }
}

.demo-warter {
  border-radius: 8px;
  margin: 5px;
  background-color: #ffffff;
  padding: 8px;
  position: relative;
  // width: 400rpx;
}

.demo-title {
  font-size: 25rpx;
  margin: 5px;
  font-weight: 600;
  color: $u-main-color;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 40rpx;
}
</style>
